import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Md5} from 'ts-md5';
import {UserDetails} from '../UserDetails';
import {UserAccount} from '../../header/header.component';

declare var $: any;

@Injectable({
  providedIn: 'root'
})
export class UserService {

  constructor(private http: HttpClient) {
  }

  public login(username: string, password: string) {
    password = Md5.hashStr(password).toString().toUpperCase();
    this.http.post('/auth/user/login', {'username': username, 'password': password}).subscribe(result => {
      if (result['success']) {
        this.getUserInfo();
        // 关闭登录窗口
        const loginWindow = $('.openform');
        if (loginWindow !== undefined) {
          loginWindow.attr('class', '');
        }
      } else {
        alert(result['message']);
      }
    });
  }


  public login2(username: string, password: string) {
    password = Md5.hashStr(password).toString().toUpperCase();
    this.http.post('/auth/user/login', {'username': username, 'password': password}).subscribe(result => {
      if (result['success']) {
        this.http.get('/user/details').subscribe(info => {
          localStorage.setItem('uid', info['id']);
          userDetails.nickname = info['nickname'];
          userDetails.username = info['username'];
          userDetails.email = info['email'];
          userDetails.gender = info['gender'];
          userDetails.head = info['head'];
          userDetails.lastLoginTime = info['lastLoginTime'];
          userDetails.phone = info['phone'];
          userDetails.birthday = info['birthday'];
          userDetails.location = info['location'];
          userDetails.id = info['id'];
          userStatus.isLogin = true;
          userStatus.uid = info['id'];
          window.location.href = '/';
        });
      } else {
        alert(result['message']);
      }
    });
  }

  public register(user: UserAccount) {
    this.http.post('/user/register', user).subscribe(res => {
      if (res['success']) {
        this.login2(user.username, user.password);
      } else {
        alert(res['message']);
      }
    });
  }

  public getUserInfo() {
    this.http.get('/user/details').subscribe(info => {
      localStorage.setItem('uid', info['id']);
      userDetails.nickname = info['nickname'];
      userDetails.username = info['username'];
      userDetails.email = info['email'];
      userDetails.gender = info['gender'];
      userDetails.head = info['head'];
      userDetails.lastLoginTime = info['lastLoginTime'];
      userDetails.phone = info['phone'];
      userDetails.birthday = info['birthday'];
      userDetails.location = info['location'];
      userDetails.id = info['id'];
      userStatus.isLogin = true;
      userStatus.uid = info['id'];
    });
  }

  public save(userInfo: UserDetails, func: Function) {
    this.http.post('/user/save', userInfo).subscribe(result => {
      func(result);
      this.getUserInfo();
    });
  }

  clearCookie() {
    const keys = document.cookie.match(/[^ =;]+(?=\=)/g);
    if (keys) {
      for (let i = keys.length; i--;) {
        document.cookie = keys[i] + '=0;path=/;expires=' + new Date(0).toUTCString();
        document.cookie = keys[i] + '=0;path=/;domain=' + document.domain + ';expires=' + new Date(0).toUTCString();
        document.cookie = keys[i] + '=0;path=/;domain=kevis.com;expires=' + new Date(0).toUTCString();
      }
    }
  }

  public logout() {
    window.location.href = '/';
    localStorage.clear();
    this.clearCookie();
    userDetails = new UserDetails();
    userStatus = {'isLogin': false, 'uid': ''};
  }

  changePassword(rawPwd: string, newPwd: string) {
    rawPwd = Md5.hashStr(rawPwd).toString().toUpperCase();
    newPwd = Md5.hashStr(newPwd).toString().toUpperCase();
    this.http.post('/user/changePwd', {'rawPwd': rawPwd, 'newPwd': newPwd}).subscribe(result => {
      alert(result['message']);
    });
  }


}

export let userDetails: UserDetails = new UserDetails();
export let userStatus = {'isLogin': false, 'uid': ''};
